package com.mt.sdk.ble.base;

import java.util.UUID;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.model.BLEBaseAction;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.ble.model.WriteCharactAction;
import com.mt.sdk.ble.model.WriteCharactWithAckAction;
import com.mt.sdk.ble.model.WriteDescriptorAction;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.os.Build;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MTSeriaBase extends BLEBase {
	/*
	 * 连接
	 * mac：蓝牙mac地址(通过mMTBLEDevice.getDevice().getAddress()获得)
	 * retryTimes：连接失败后，尝试重试连接次数(推荐2)
	 * isScan：是否需要扫描(推荐false)
	 * callback：结果回调
	 */
	private boolean connectfail = false;
	private ErroCode connectfail_errocode;
	
	public ErroCode connect(String mac, int retryTimes, boolean isScan, CallBack callback) {
		this.callback = callback;
		return super.connect(mac, retryTimes, isScan);
	}
	
	public ErroCode connect(String mac, int retryTimes, int rssi, CallBack callback) {
		this.callback = callback;
		return super.connectWithRssi(mac, retryTimes, rssi);
	}
	
	// 查看是否有可用连接
	private boolean MTSeriaConnect = false;
	public boolean isMTSeriaConnect(){
		return MTSeriaConnect;
	}
	
	// 获取特定服务
	private static final String DATA_SERVICE_UUID = "0000f1f0-0000-1000-8000-00805f9b34fb";
	private static final String TXD_CHARACT_UUID = "0000f1f1-0000-1000-8000-00805f9b34fb";
	private static final String RXD_CHARACT_UUID = "0000f1f2-0000-1000-8000-00805f9b34fb";
	private static final String CMD_SERVICE_UUID = "0000f2f0-0000-1000-8000-00805f9b34fb";
	private static final String ATSEND_CHARACT_UUID = "0000f2f1-0000-1000-8000-00805f9b34fb";
	private static final String ATRECV_CHARACT_UUID = "0000f2f2-0000-1000-8000-00805f9b34fb";
	private BluetoothGattCharacteristic txd_charact;
	private BluetoothGattCharacteristic rxd_charact;
	private BluetoothGattCharacteristic atsend_charact;
	private BluetoothGattCharacteristic atrecv_charact;

	private boolean getCharacts() {
		BluetoothGattService data_service = getService(DATA_SERVICE_UUID);
		BluetoothGattService cmd_service = getService(CMD_SERVICE_UUID);
		if ((data_service == null) || (cmd_service == null)) { // 服务获取失败的情况
			return false;
		}

		txd_charact = data_service.getCharacteristic(UUID.fromString(TXD_CHARACT_UUID));
		rxd_charact = data_service.getCharacteristic(UUID.fromString(RXD_CHARACT_UUID));

		atsend_charact = cmd_service.getCharacteristic(UUID.fromString(ATSEND_CHARACT_UUID));
		atrecv_charact = cmd_service.getCharacteristic(UUID.fromString(ATRECV_CHARACT_UUID));

		if ((txd_charact == null) || (rxd_charact == null) || (atsend_charact == null) || (atrecv_charact == null)) {
			return false;
		}

		return true;
	}

	// 添加到监听列表
	private void addTolisten() {
		addListCharact(rxd_charact);
		addListCharact(atrecv_charact);
	}

	@Override
	final protected void onCharactChanged(BluetoothGattCharacteristic characteristic, byte[] datas) {
		super.onCharactChanged(characteristic, datas);
		System.out.println("MTSeriaBase-> onCharactChanged");

		if (characteristic == rxd_charact) { // 透传数据
			if(callback != null){
				callback.onDatasRecive(rxd_charact, datas);
			}
			return;
		}
	}

	// 使能特征值的可通知属性
	private boolean enableNotify() {
		enableNotify(rxd_charact, true);
		enableNotify(atrecv_charact, true);
		BluetoothGattDescriptor descriptor = rxd_charact
				.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

		addNewAction(new WriteDescriptorAction(descriptor, new BLEBaseAction.Option(2000)) {

			@Override
			public void onSuccess() {
				super.onSuccess();
				BluetoothGattDescriptor descriptor = atrecv_charact
						.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
				descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

				addNewAction(new WriteDescriptorAction(descriptor, new Option(2000)) {
					@Override
					public void onSuccess() {
						super.onSuccess();
						addTolisten();
						MTSeriaConnect = true;
						if (callback != null) {
							callback.onConnect(ErroCode.ERROMAP.get("OK"));
						}
					}

					@Override
					public void onFail(ErroCode erro) {
						super.onFail(erro);
						System.out.println("mBLEBase2.addNewAction2 onFail");
						connectfail = true;
		                connectfail_errocode = ErroCode.ERROMAP.get("enablenotifyerro");
						disConnect();
					}
				});
			}

			@Override
			public void onFail(ErroCode erro) {
				super.onFail(erro);
				System.out.println("mBLEBase2.addNewAction1 onFail");
				connectfail = true;
                connectfail_errocode = ErroCode.ERROMAP.get("enablenotifyerro");
				disConnect();
			}

		});
		return true;
	}

	@Override
	final protected void onBaseConnect(ErroCode errocode) {
		super.onBaseConnect(errocode);
		if (errocode.getCode() != 0) { // 连接失败的情况
//			disConnect();
			if (callback != null) {
				callback.onConnect(errocode);
			}
			return;
		}

		if (!getCharacts()) { // 获取特定服务失败的情况
			connectfail = true;
			connectfail_errocode = ErroCode.ERROMAP.get("getcharacterro");
			disConnect();
			return;
		}

		if (!enableNotify()) { // 使能可通知失败的情况
			System.out.println("enableNotify");
			connectfail = true;
			connectfail_errocode = ErroCode.ERROMAP.get("enablenotifyerro");
			disConnect();
			return;
		}
	}

	@Override
	final protected void reTryConnect(int lasttimes) {
		super.reTryConnect(lasttimes);
		if(callback != null){
			callback.reTryConnect(lasttimes);
		}
	}

	@Override
	final protected void onDisConnect(ErroCode errocode) {
		super.onDisConnect(errocode);
		MTSeriaConnect = false;
		if(callback != null){
			callback.onDisConnect(errocode);
		}
	}

	@Override
	final protected void onManualDisConnect(ErroCode errocode) {
		super.onManualDisConnect(errocode);
		MTSeriaConnect = false;
		if(connectfail){
			if(callback != null){
				callback.onConnect(connectfail_errocode);
			}
			return;
		}
		if(callback != null){
			callback.onManualDisConnect(connectfail_errocode);
		}
	}

	public MTSeriaBase(Context context, MTBLEManager manager) {
		super(context, manager);
	}

	// 添加写数据操作
	public boolean addWriteDatasAction(WriteCharactAction action) {
		action.setCharact(txd_charact);
		addNewAction(action);
		return true;
	}

	// 添加写命令操作
	public boolean addWriteCmdsAction(WriteCharactWithAckAction action){
		action.setSendCharact(atsend_charact);
		action.setReviceCharact(atrecv_charact);
		addNewAction(action);
		return true;
	}
	// 添加写数据带回复操作
	public boolean addWriteDatasWithAckAction(WriteCharactWithAckAction action){
        action.setSendCharact(txd_charact);
        action.setReviceCharact(rxd_charact);
        addNewAction(action);
        return true;
    }

	private CallBack callback;

	// 回调
	public static interface CallBack {
		public void onConnect(ErroCode errocode);

		public void reTryConnect(int lasttimes);

		public void onDisConnect(ErroCode errocode);

		public void onManualDisConnect(ErroCode errocode);
		
		public void onDatasRecive(BluetoothGattCharacteristic rxd_charact, byte[] datas);
	}
}
